<?php

/**
 * Html tag generator.
 *
 * @author     Mon Zafra <monzee at gmail>
 * @copyright  (c)2009 Mon Zafra
 * @category   Mz
 * @package    Mz_Helper
 * @subpackage View
 * @license    http://mz-project.googlecode.com/svn/trunk/LICENSE    MIT License
 * @version    SVN: $Id: Html.php 3 2009-02-18 18:55:27Z monzee $
 */
class Mz_Helper_View_Html
{
    const OPEN = 1;
    const CLOSE = 2;
    const TEXT_NODE = 4;

    protected $_tag;
    protected $_attributes = array();
    protected $_textNode;
    protected $_selfClose = false;
    protected $_mode = 7;
    protected $_selfClosingTags = array(
        'link', 'meta', 'input', 'hr', 'br', 'img'
    );

    public function html($tag)
    {
        $this->_tag = strtolower($tag);
        if (in_array($tag, $this->_selfClosingTags)) {
            $this->_selfClose = true;
        }
        return $this;
    }

    public function textNode($text)
    {
        $this->_textNode = $text;
        return $this;
    }

    public function setAttribute($attrib, $value)
    {
        $this->_attributes[trim($attrib)] = $value;
        return $this;
    }

    public function open()
    {
        $this->_mode = self::OPEN;
        return $this;
    }

    public function close()
    {
        $this->_mode = self::CLOSE;
        return $this;
    }

    public function __call($attrib, $args)
    {
        return $this->setAttribute($attrib, $args[0]);
    }

    public function __toString()
    {
        $attributes = array();
        foreach ($this->_attributes as $attrib => $value) {
            $attributes[] = $attrib . '="' . htmlspecialchars($value) . '"';
        }

        $open = '<' . $this->_tag
              . (!empty($attributes) ? ' ' . implode(' ', $attributes) : '')
              . ($this->_selfClose ? ' />' : '>');

        $close = ($this->_selfClose ? '' : '</' . $this->_tag . '>');

        $ret = '';

        if ($this->_mode & self::OPEN) {
            $ret .= $open;
        }
        if (($this->_mode & self::TEXT_NODE) && !$this->_selfClose) {
            $ret .= $this->_textNode;
        }
        if ($this->_mode & self::CLOSE) {
            $ret .= $close;
        }

        return $ret;
    }

}
